package com.smartens.boit.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Looper;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.smartens.boit.MyApplication2;
import com.smartens.boit.R;
import com.smartens.boit.adapter.AutoAdapter;
import com.smartens.boit.bean.LightDetailBean;
import com.smartens.boit.bean.ListBeans;
import com.smartens.boit.bean.ListParameterBean;
import com.smartens.boit.bean.RecordDetail;
import com.smartens.boit.bean.RecordeDetail_datd;
import com.smartens.boit.bean.TimeUpdateBean;
import com.smartens.boit.fragment.viewmode.AutoControlFragmentViewModel;
import com.smartens.boit.util.CustomBrightnessPlanDialog;
import com.smartens.boit.util.CustomTimeDialog;
import com.smartens.boit.util.DialogBrightness;
import com.smartens.boit.util.DialogTime;
import com.smartens.boit.util.HttpHelper;
import com.smartens.boit.util.Pickers;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;

/**
 * @Description 自动控制
 * @Author songtt
 * @Date 2021/3/4
 */
public class AutoControlFragment extends Fragment {
    private static final String TAG = "AutoControlFragment";
    private RecyclerView recyclerView;
    private AutoAdapter recycleAdapter;
    public DialogBrightness dialogBrightness;
    public CustomTimeDialog dialogTime;
    public CustomBrightnessPlanDialog customBrightPlanDialog;
    public FragmentManager fragmentManager;
    private LinearLayoutManager mLinearLayoutManager;
    private List<List<LightDetailBean>> mList = new ArrayList<>();
    private HttpHelper helper;
    private TextView save;
    private TextView unSave;
    private LinearLayout linTime;
    private TextView textTime;
    private String openTime = "00:00";
    private String closeTime = "00:00";
    private Boolean isOpen = false;
    private static final String ID1 = "d3bf7f44-2f8b-46ba-add2-7baef1bddabe";
    private static final String ID2 = "b55596b6-c560-4c87-b46b-bafa50b272f4";
    AutoControlFragmentViewModel viewModel;
    private List<RecordeDetail_datd> groupListData = new ArrayList<>();
    private List<Pickers> pickersList = new ArrayList<>();
    private final CountDownLatch countDownLatch = new CountDownLatch(2);
    private List<LightDetailBean> result1 = new ArrayList<>();
    private List<LightDetailBean> result2 = new ArrayList<>();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_auto_control, container, false);
        recyclerView = view.findViewById(R.id.rv_auto);
        linTime = view.findViewById(R.id.lin_time);
        textTime = view.findViewById(R.id.tv_time);
        save = view.findViewById(R.id.tv_save);
        unSave = view.findViewById(R.id.tv_unsave);
        helper = HttpHelper.getInstance();
//        getProjectList();
        initView();
        viewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(requireActivity().getApplication())).get(AutoControlFragmentViewModel.class);
        viewModel.getDeviceOnOffTimeDetail(true).observe(getViewLifecycleOwner(), timeData -> {
            if (timeData != null) {
                openTime = timeData.getDeviceOpenTime();
                closeTime = timeData.getDeviceCloseTime();
                textTime.setText(openTime + "-" + closeTime);
            }
        });

        viewModel.getBrightnessAdjustPlans(true).observe(getViewLifecycleOwner(), pickers -> {
            if (pickers != null && pickers.size() != 0) {
                pickersList.clear();
                pickersList.addAll(pickers);
            }
        });

        viewModel.getGroupListData(true).observe(getViewLifecycleOwner(), result -> {
            if (result == null) return;
            groupListData.clear();
            groupListData.addAll(result);
            if (result.size() == 2) {
                getProjectDetail1(result.get(1).getProjectID());
                getProjectDetail2(result.get(0).getProjectID());
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mList.clear();
                mList.add(result1);
                mList.add(result2);
                String brightness = result1.get(0).getProjectParameterList().get(0).getBrightness();
                Log.e(TAG,"亮度："+brightness);
                recycleAdapter.setData(mList);
                recycleAdapter.notifyDataSetChanged();
            } else {
                Toast.makeText(getActivity(), "暂无方案", Toast.LENGTH_SHORT).show();
            }
        });
        return view;
    }

    public void initView() {
        mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recycleAdapter = new AutoAdapter(mList, getContext());
        //设置布局管理器
        recyclerView.setLayoutManager(mLinearLayoutManager);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);
        //设置时间和亮度
        recycleAdapter.setOnBrightClickListener02(new AutoAdapter.OnBright02ClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                TextView textView = itemView.findViewById(R.id.tv_bright2);
                brightDialog(textView, 2, position);
            }
        });
        recycleAdapter.setOnBright01ClickListener(new AutoAdapter.OnBright01ClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                TextView textView = itemView.findViewById(R.id.tv_bright1);
                brightDialog(textView, 1, position);
            }
        });
        recycleAdapter.setOnBright03ClickListener(new AutoAdapter.OnBright03ClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                TextView textView = itemView.findViewById(R.id.tv_bright3);
                brightDialog(textView, 3, position);
            }
        });

        recycleAdapter.setOnControlClickListener(new AutoAdapter.OnControlClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                CheckBox radioButton = itemView.findViewById(R.id.sw_up);
                radioButton.setEnabled(false);
                LinearLayout linearLayoutGradual = itemView.findViewById(R.id.lin_gradual);
                if (radioButton.isChecked()) {
                    linearLayoutGradual.setVisibility(View.GONE);
                    radioButton.setChecked(false);
                    mList.get(position).get(0).setDimmingMode("1");
                    mList.get(position).get(1).setDimmingMode("1");
                    mList.get(position).get(2).setDimmingMode("1");
                } else {
                    linearLayoutGradual.setVisibility(View.VISIBLE);
                    radioButton.setChecked(true);
                    mList.get(position).get(0).setDimmingMode("0");
                    mList.get(position).get(1).setDimmingMode("0");
                    mList.get(position).get(2).setDimmingMode("0");
                }
            }
        });
        linTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timeDialog();
            }
        });

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开启自动控制
                openAuto();
            }
        });

        recycleAdapter.setOnLlAdjustPlanListener(new AutoAdapter.OnLlAdjustBrightnessPlanClickListener() {
            @Override
            public void onClickListener(int position) {
                showCustomBrightPlanDialog(position);
            }
        });
    }

    private void showCustomBrightPlanDialog(int position) {
        if (fragmentManager == null) {
            fragmentManager = requireActivity().getSupportFragmentManager();
        }
        if (position == 0) {
            //分组1 IUB
            String projectName = null;
            if (groupListData != null && groupListData.size() > 1) {
                projectName = groupListData.get(1).getProjectName();
            }
            customBrightPlanDialog = CustomBrightnessPlanDialog.newInstance(pickersList, projectName);
        } else if (position == 1) {
            //分组2 IOT
            String projectName = null;
            if (groupListData != null && groupListData.size() > 1) {
                projectName = groupListData.get(0).getProjectName();
            }
            customBrightPlanDialog = CustomBrightnessPlanDialog.newInstance(pickersList, projectName);
        } else {
            //todo 暂无
        }

        if (customBrightPlanDialog != null && !customBrightPlanDialog.isAdded()) {
            customBrightPlanDialog.show(fragmentManager, "customBrightPlanDialog");
            customBrightPlanDialog.setDialogCallback(new CustomBrightnessPlanDialog.DialogCallback() {
                @Override
                public void confirm(@Nullable String projectId) {
                    EditDeviceGroupLight(projectId, String.valueOf(position + 1));
                    viewModel.getBrightnessAdjustPlans(true);
                    customBrightPlanDialog.dismissDialog();
                }
            });
        }


    }

    public void brightDialog(TextView textView, int sort, int pos) {

        if (fragmentManager == null) {
            fragmentManager = requireActivity().getSupportFragmentManager();
        }
        dialogBrightness = new DialogBrightness();
        if (!dialogBrightness.isAdded()) {
            dialogBrightness.show(fragmentManager, "DialogFragment");
        }
        dialogBrightness.setDialogCallback(new DialogBrightness.DialogCallback() {
            @Override
            public void confirm(String hour, String beat, String min) {
                textView.setText("时间 " + hour + ":" + min + " 亮度 " + beat);
                dialogBrightness.dismissDialog();

                String bright = beat.substring(0, beat.length() - 1);
                ListParameterBean listParameterBean = new ListParameterBean();
                listParameterBean.setTime(hour + ":" + min);
                listParameterBean.setSort(String.valueOf(sort));
                listParameterBean.setClosetime(mList.get(pos).get(sort - 1).getProjectParameterList().get(0).getClosetime());
                listParameterBean.setBrightness(bright);
                mList.get(pos).get(sort - 1).getProjectParameterList().set(0, listParameterBean);

//                mList.get(pos).get(sort-1).getProjectParameterList().get(0).setTime(hour+":"+min);
//                mList.get(pos).get(sort-1).getProjectParameterList().get(0).setTime(beat.substring(1,beat.indexOf("%")));


                recycleAdapter.setData(mList);
//                recycleAdapter.notifyDataSetChanged();
            }
        });

    }

    public void timeDialog() {
        if (fragmentManager == null) {
            fragmentManager = requireActivity().getSupportFragmentManager();
        }
        if (dialogTime == null) {
            dialogTime = new CustomTimeDialog();
        }
        String startHour = "00:00";
        String startMin = "00:00";
        String endHour = "00:00";
        String endMin = "00:00";
        if (openTime != null) {
            String[] split = openTime.split(":");
            if (split.length == 2) {
                startHour = split[0];
                startMin = split[1];
            }
        }
        if (closeTime != null) {
            String[] split = closeTime.split(":");
            if (split.length == 2) {
                endHour = split[0];
                endMin = split[1];
            }
        }
        Log.i("AutoControlFragment:", "startHour:" + startHour + ",startMin:" + startMin + ",endHour:" + endHour + ",endMin:" + endMin);
        TimeUpdateBean timeUpdateBean = new TimeUpdateBean(startHour, startMin, endHour, endMin);
        dialogTime.setTimeUpdateBean(timeUpdateBean);
        dialogTime.setDialogCallback(new DialogTime.DialogCallback() {
            @Override
            public void confirm(String startHours, String startMin, String endHours, String endMin) {
                textTime.setText(String.format("%s:%s-%s:%s", startHours, startMin, endHours, endMin));
                openTime = startHours + ":" + startMin;
                closeTime = endHours + ":" + endMin;
                dialogTime.dismissDialog();
            }
        });

        if (!dialogTime.isAdded()) {
            dialogTime.show(fragmentManager, "DialogFragment");
        }

    }

    /**
     * 开启自动控制
     */
    public void openAuto() {
        helper.EditDeviceGateWayOn(openTime, closeTime, ":", new HttpHelper.HttpCallBack<String>() {
            @Override
            public void onSuccess(List<String> result) {
                Log.i("==openAuto===切换成功", result.get(0));
                makeToast("操作成功");
            }

            @SuppressLint("LongLogTag")
            @Override
            public void onFailure(final String message) {
                makeToast("操作失败");
                //   Log.v("=====openAuto==onFailure", message);
            }
        });
    }

    /**
     * 选择分组控制方案
     */
    public void EditDeviceGroupLight(String id, String num) {
        helper.EditDeviceGroupLight("32FFD7055643373914721851", num, id, new HttpHelper.HttpCallBack<String>() {
            @SuppressLint("LongLogTag")
            @Override
            public void onSuccess(List<String> result) {
                Log.i("=====EditDeviceGroupLight成功", result.get(0));
                SystemClock.sleep(300);
                //刷新整个调光方案,刷新整个页面
                viewModel.getGroupListData(true);
                makeToast("操作成功");
            }

            @SuppressLint("LongLogTag")
            @Override
            public void onFailure(final String message) {
                makeToast("操作失败");
                //   Log.v("=====EditDeviceGroupLight==onFailure", message);
            }
        });
    }

    public void getProjectList() {

//        helper.GetProjectList(new HttpHelper.HttpCallBack<ListBeans>() {
//            @SuppressLint("LongLogTag")
//            @Override
//            public void onSuccess(List<ListBeans> result) {
//                Log.v("=====GetProjectDetail==获取方案成功", String.valueOf(result.size()));
//
//            }
//
//            @SuppressLint("LongLogTag")
//            @Override
//            public void onFailure(final String message) {
//                // Toast.makeText(getActivity(), "获取方案失败" , Toast.LENGTH_LONG).show();
//            }
//        });
    }


    /**
     * 控制方案详情
     *
     * @param id
     */
    public void getProjectDetail1(String id) {

        helper.GetProjectDetailResult(id, new HttpHelper.HttpCallBack<LightDetailBean>() {
            @SuppressLint("LongLogTag")
            @Override
            public void onSuccess(List<LightDetailBean> result) {
                for (int i = 0; i < result.size(); i++) {
                    result.get(i).setProjectId(id);
                }
                result1.clear();
                result1.addAll(result);
                countDownLatch.countDown();
//                mList.add(result);
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        recycleAdapter.setData(mList);
//                        recycleAdapter.notifyDataSetChanged();
//                    }
//                });
            }

            @SuppressLint("LongLogTag")
            @Override
            public void onFailure(final String message) {
                // Toast.makeText(getActivity(), "获取方案失败" , Toast.LENGTH_LONG).show();
            }
        });
    }

    public void getProjectDetail2(String id) {

        helper.GetProjectDetailResult(id, new HttpHelper.HttpCallBack<LightDetailBean>() {
            @SuppressLint("LongLogTag")
            @Override
            public void onSuccess(List<LightDetailBean> result) {
                Log.v("=====GetProjectDetail==获取方案成功1", "==获取方案成功");
                for (int i = 0; i < result.size(); i++) {
                    result.get(i).setProjectId(id);
                }
                result2.clear();
                result2.addAll(result);
                countDownLatch.countDown();
//                mList.add(result);
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        recycleAdapter.setData(mList);
//                        recycleAdapter.notifyDataSetChanged();
//                    }
//                });
            }

            @SuppressLint("LongLogTag")
            @Override
            public void onFailure(final String message) {
                Log.v("=====GetProjectDetail2==获取方案失败", message);
                // Toast.makeText(getActivity(), "获取方案失败" , Toast.LENGTH_LONG).show();
            }
        });
    }


    public void makeToast(String message) {
        Looper.prepare();
        Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
        Looper.loop();
    }


}